'''
Created on 2011/03/10

@author: Administrator
'''

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson
from util.GaeEncoder import GaeEncoder
from core.RecentEvaluation import RecentEvaluationClass
from core.PlayTime import PlayTimeClass
from core.PlayerInfo import PlayerInfoClass
from core.EvaluatedFriends import EvaluatedFriendsClass
from util.models import Field
from util.deleteDatabase import RequestCheck
from util.deleteDatabase import InitializeDBs
from util.deleteDatabase import RemoveAll
from signed_request import signed_request

import random

class RequestField(webapp.RequestHandler):
    def __init__(self):
        self.UPPER_LEVEL=3.5
        self.EACH_FIELD_NUM=3
 
    
    @signed_request      
    def get(self):
        candField = self.getFieldNum()
        g_list = Field.gql('WHERE fieldNum IN :1 ORDER BY fieldID LIMIT 10',candField)
        g_listJson = GaeEncoder().encode(g_list) 
        self.response.content_type = "application/json"
        self.response.out.write(g_listJson)
    
    def getFieldNum(self):
        # [NEED TO MODIFY] if more field will be added, need to modify. 
        fields = [[1,2],[2,3],[1,3]]
        candNum = random.randint(0,self.EACH_FIELD_NUM-1)
        return fields[candNum]

class RequestUpdateStaticInfo(webapp.RequestHandler):
    @signed_request
    def post(self):
        myID = self.request.get('myID')
        ###    gender = self.request.get('gender')
        playerIDList = self.request.get('playerIDList')
        
        playerIDListJSON = simplejson.loads(playerIDList, encoding=False)
         
        ef = EvaluatedFriendsClass()
        ef.updateEvaluatedFriends(myID,playerIDListJSON) 
        
        ## update play time
        pt = PlayTimeClass()
        pt.updatePlayTime(myID)

        ### if not yet set gender, set now
        ## if(pt.getTimePlay()==1):
        ##    pi=PlayerInfoClass()
        ##    pi.setGender(myID, gender)

class RequestStoreResult(webapp.RequestHandler):
    @signed_request
    def post(self):       
        myID = self.request.get('myID')
        fieldsList = self.request.get('fieldsList')
        fullResultList = self.request.get('fullResultList')
        fieldsListJSON = simplejson.loads(fieldsList, encoding=False)
        fullResultListJSON = simplejson.loads(fullResultList, encoding=False)
        
        ### [NEED TO MODIFY] if convertResultList take much time, this process should be implemented on client logic(Javascript)
        playersResult = self.convertResultList(myID, fieldsListJSON, fullResultListJSON)
        
        re = RecentEvaluationClass()
        re.updatePlayersEvaluations(playersResult['playersEvaluations'])

        pi=PlayerInfoClass()
        pi.updatePlayersPoints(playersResult['playersPoints'],playersResult['playersPlayNums'])
         
    ## convert from fieldListJSON and fullResultListJSON to player point, playnum, recentevaluation
    #  myID: player's ID
    #  fieldsListJSON: The field ID list using in this game with JSON format
    #  fullResultListJSON: key: fieldID, value: players' ID array as result of each field 
    def convertResultList(self,myID,fieldsListJSON,fullResultListJSON):
        playersResult={}
        playersPoints = {}
        playersPlayNums={}
        playersEvaluations = {}
        PRIZE=3
        
        for fieldID in fieldsListJSON:
            result = fullResultListJSON[fieldID]
            rank=0
            
            for player in result:
                if player not in playersPoints:
                    playersPoints[player] = [0,0,0,0,0]
                    playersPlayNums[player] = [0,0,0,0,0]
                             
                fieldCategory = fieldsListJSON[fieldID]['fieldCategory']
                playersPoints[player][fieldCategory]+=(5-rank)
                playersPlayNums[player][fieldCategory]+=1
                rank+=1
                
                if player not in playersEvaluations:
                    playersEvaluations[player]=[]
                
                if rank<=PRIZE:
                    playerEvaluation={}
                    playerEvaluation['evaluaterID']=myID
                    playerEvaluation['evaluatedID']=player
                    playerEvaluation['fieldID']=fieldID
                    playerEvaluation['fieldTitle']=fieldsListJSON[fieldID]['fieldTitle']
                    playerEvaluation['rank']=rank
                    playersEvaluations[player].append(playerEvaluation.copy())
                
        playersResult['playersPoints']=playersPoints
        playersResult['playersPlayNums']=playersPlayNums
        playersResult['playersEvaluations']=playersEvaluations.copy()
        
        return playersResult
    
class RequestPlayerInfo(webapp.RequestHandler):
    @signed_request  
    def post(self):       
        myID = self.request.get('myID')
        pi = PlayerInfoClass()
        myInfo=pi.getMyInfo(myID)
        pt=PlayTimeClass()
        re=RecentEvaluationClass()
        personalResultInfo={"playerInfo":myInfo['playerInfo'],"evaluations":re.getRecentEvaluations(myID), "playTimeInfo":pt.getPlayTime(myID),"synastryList":myInfo['synastryList'],"fortuneList":myInfo['fortuneList']}
        resultJson = GaeEncoder().encode(personalResultInfo) 
        self.response.content_type = "application/json"
        self.response.out.write(resultJson)

application = webapp.WSGIApplication([('/request/field', RequestField),('/request/storeresult', RequestStoreResult),('/request/updatestatic', RequestUpdateStaticInfo),('/request/playerinfo', RequestPlayerInfo),('/check/(.*)', RequestCheck),('/dbutil/(.*)',InitializeDBs),('/remove/(.*)',RemoveAll)], debug=True)


def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
